import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'

export const request = (options: object) => {
  return new Promise((resolve, reject) => {
    // axios实例
    const service = axios.create({
      baseURL: '/api/private/v1/', // 所有的请求地址前缀部分
      timeout: 300000, //五分钟超时
    })
    //请求拦截器
    service.interceptors.request.use(
      (response) => {
        response.headers.Authorization = useCounterStore().token

        return response //请求成功返回response
      },
      (error) => {
        //请求失败则显示错误状态
        console.log(error.message)
        return Promise.reject(error)
      },
    )
    // 响应拦截器
    service.interceptors.response.use(
      (response) => {
        switch (response.data.meta.status) {
          case 200:
            ElMessage.success(response.data.meta.msg)
            break
          case 201:
            ElMessage.success(response.data.meta.msg)
            break
          case 204:
            ElMessage.success(response.data.meta.msg)
            break
          case 400:
            ElMessage.error(response.data.meta.msg)
            break
          case 401:
            ElMessage.error(response.data.meta.msg)
            break
          case 403:
            ElMessage.error(response.data.meta.msg)
            break
          case 404:
            ElMessage.error(response.data.meta.msg)
            break
          case 422:
            ElMessage.error(response.data.meta.msg)
            break
          case 500:
            ElMessage.error(response.data.meta.msg)
            break
          default:
            ElMessage.warning(response.data.meta.msg)
            break
        }

        //请求成功返回response.data
        return response
      },
      (error) => {
        console.log('响应失败', error.message)
        return Promise.reject(error) //请求失败则返回错误信息
      },
    )
    // 请求处理
    service(options)
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

// 导出request
export default request
